<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\SettingRequest;
use App\Http\Resources\SettingCollectionResource;
use App\Http\Resources\SettingResource;
use App\Models\Setting;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    /**
     * 配置列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $params = $request->all();

        $settings = Setting::query()->when($params['name'] ?? '', function ($query, $name) {
            $like = '%' . $name . '%';
            $query->where('key', 'like', $like)->orWhere('label', 'like', $like);
        })->orderBy('id', 'desc')->paginate($params['size'] ?? 10);

        return $this->success(new SettingCollectionResource($settings));
    }

    /**
     * 新增配置
     * @param SettingRequest $request
     * @return mixed
     */
    public function store(SettingRequest $request)
    {
        Setting::create(array_filter($request->only(['key', 'label', 'value'])));

        return $this->created('配置新增成功');
    }

    /**
     * 配置详情
     * @param Setting $setting
     * @return mixed
     */
    public function show(Setting $setting)
    {
        return $this->success(new SettingResource($setting));
    }

    /**
     * 更新配置
     * @param SettingRequest $request
     * @param Setting $setting
     * @return mixed
     */
    public function update(SettingRequest $request, Setting $setting)
    {
        $setting->fill(array_filter($request->only(['key', 'label', 'value'])));
        $setting->save();

        return $this->success(new SettingResource($setting));
    }

    /**
     * 删除配置
     * @param Setting $setting
     * @return mixed
     * @throws \Exception
     */
    public function destroy(Setting $setting)
    {
        if ($setting->id === 1) {
            return $this->failed('第一个配置不能被删除');
        }
        $setting->delete();
        return $this->success('配置删除成功');
    }
}
